import { Button, Flex, Form, Input, Select, Space, Table , Modal, message } from 'antd';
import style from '../css/Blacklistmanagement.module.scss'
import { MinusCircleOutlined, PlusOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons';
import type { TableColumnsType, TableProps } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { blacklist, blacklistdel, blacklistinsert, blacklistserach } from '../utils/request';
import Padination from '../components/Pagination';
import { exportTableToPdf } from '../components/exportToPdf'
function Blacklistmanagement() {
    const [form] = Form.useForm();
    const [formOne] = Form.useForm();
    // 黑名单表格
    interface DataType {
        blacklist_id: React.Key;
        PatientIDCard: string;
        IDCard: string;
        name: string;
        brokentimes: number;
        status: string;
    }

    const columns: TableColumnsType<DataType> = [
        {
            title: '就诊卡号',
            dataIndex: 'Medicalcard',
            width: 222
        },
        {
            title: '证件号',
            dataIndex: 'Idcard',
            width: 242
        },
        {
            title: '患者姓名',
            dataIndex: 'name',
            width: 165
        },
        {
            title: '爽约次数',
            dataIndex: 'brokentimes',
            width: 151
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 113,
            render: (text) => (
                text == '未限制' ?
                    <p style={{ color: '#0468ff' }}>{text}</p>
                    :
                    <p style={{ color: '#fa6a1c' }}>{text}</p>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 156,
            render: (_,record) => (
                <Space size="small">
                    <a onClick={() => details(record)}>详情</a>
                    <a onClick={() => remove(record)}>移出黑名单</a>
                </Space>
            ),
        },
    ];


    useEffect(()=>{
        blacklist().then(res=>{
            setData(res.data.slice(0,10))
            setMockData(res.data)
        }).catch(err=>{
            console.log(err)
        })
    },[])
    const [mockData,setMockData] = useState<DataType[]>([])
    const [data,setData] = useState<DataType[]>([])
    
    //表格选择框事件   
    // rowSelection object indicates the need for row selection
    const [selectedRows,setSelectedRows] =useState<DataType[]>([])
    const rowSelection: TableProps<DataType>['rowSelection'] = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            setSelectedRows(selectedRows)
        },
    };
    // 爽约详情表格
    // 定义一个接口来描述表格中每一行的数据类型
    interface AppointmentData {
        key: string; // 这是每一行的唯一标识
        name: string; // 患者姓名
        cardNumber: string; // 就诊卡号
        Reasoncontract: string; // 预约时间
        note:string;
        // ... 可以根据需要添加更多字段
    }
    // 模拟一些预约数据
    const appointmentData: AppointmentData[] = [
        {
            key: '1',
            cardNumber: '20050869',
            name: '张晓晓',
            Reasoncontract: '挂号未就诊（就诊号：6520050869）',
            note:''
            // ... 其他数据
        },
        {
            key: '2',
            cardNumber: '20050869',
            name: '张晓晓',
            Reasoncontract: '挂号未就诊（就诊号：6520050867）',
            note:''
            // ... 其他数据
        },
        {
            key: '3',
            cardNumber: '20050869',
            name: '张晓晓',
            Reasoncontract: '挂号未就诊（就诊号：6520050866）',
            note:''
            // ... 其他数据
        },
    ];

    // 定义表格的列
    const columnstwo: any[] = [
        {
            title: '就诊卡号',
            dataIndex: 'cardNumber',
            key: 'cardNumber',
            width:105
        },
        {
            title: '患者姓名',
            dataIndex: 'name',
            key: 'name',
            width:145
        },
        {
            title: '爽约原因',
            dataIndex: 'Reasoncontract',
            key: 'Reasoncontract',
            width:291
        },
        {
            title: '备注',
            dataIndex: 'note',
            key: 'note',
            width:133
        },
        // ... 可以根据需要添加更多列
    ];
    // 重置
    const reset = () => {
        blacklist().then(res=>{
            setData(res.data.slice(0,10))
            setMockData(res.data)
            form.resetFields()
        }).catch(err=>{
            console.log(err)
        })
    }
    // 搜索
    const search = () => {
        form.validateFields().then(values => {
            console.log('Validated values: ', values);
            blacklistserach(values).then(res=>{
                setData(res.data.slice(0,10))
                setMockData(res.data)
            }).catch(err=>{
                console.log(err)
            })
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    }
    // 批量移除黑名单
    const removebatch = () => {
        setIsDeleteModalVisible(true)
    }
    // 导出
    const tableRef = useRef<HTMLDivElement>(null);
    const exports = async () => {
        if (tableRef.current) {
            await exportTableToPdf(tableRef.current, 'table_data.pdf');
          }
    }
    // 新增
    const insert = () => {
        setBlacklistshow(true)
    }
    // 详情
    const [isdetails,setIsDetails] = useState(false)
    const details = (record:any) => {
        console.log('详情',record)
        setIsDetails(true)
    }
    const detailsClose=()=>{
        setIsDetails(false)
    }
    // 移除黑名单
    const remove = (record:any) => {
        setIsDeleteModalVisible(true)
        setSelectedRows([record])
    }
    // 移除黑名单对话框
    const [isDeleteModalVisible,setIsDeleteModalVisible] = useState(false)
    const [removeloading,setRemoveloading] = useState(false)
    const removeOk=()=>{
        setRemoveloading(true)
        setTimeout(() => {
            
            blacklistdel({
                selectedRows
            }).then(res=>{
                setData(res.data.slice((page.current-1)*page.pageSize,(page.current*page.pageSize)))
                setMockData(res.data)
                setRemoveloading(false)
                message.success(`移除操作成功！`);
                setIsDeleteModalVisible(false)
            }).catch(err=>{
                console.log(err)
            })
           
        }, 2000);
    }
    const removeCancel=()=>{
        message.warning('已取消操作')
        setIsDeleteModalVisible(false)
    }
    // 新建黑名单对话框
    const [balcklistshow,setBlacklistshow] = useState(false)
    const [blacklistloading,setBlacklistloading] = useState(false)
    const balcklistcancel = () =>{
        setBlacklistshow(false)
        formOne.resetFields()
    }
    const balcklistOK = () => {
        setBlacklistloading(true)
        setTimeout(() => {
            setBlacklistloading(false)
            formOne.validateFields().then(values => {
                blacklistinsert(values).then(res=>{
                    setData(res.data.slice((page.current-1)*page.pageSize,(page.current*page.pageSize)))
                    setMockData(res.data)
                    setBlacklistshow(false)
                    formOne.resetFields()
                    message.success('黑名单添加成功')
                }).catch(err=>{
                    console.log(err)
                })
                
            }).catch(info => {
                console.log('Validate Failed:', info);
            });
        }, 2000);
    }


    // 分页传递数据 
    const [page,setPage] = useState({
        current:1,
        pageSize:10
    })
    const getshowsize = (data: any) => {
        setPage(data)
        setData(mockData.slice((data.current-1)*data.pageSize,data.pageSize*data.current))
    }
    return (
        <>
            {/* 新建黑名单对话框 */}
            <Modal
                title='新建黑名单'
                open={balcklistshow}
                width={365}
                style={{marginTop:20}}
                onCancel={balcklistcancel}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={balcklistcancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={blacklistloading} onClick={balcklistOK} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
            >
                <Form
                    form={formOne}
                >
                    <Form.Item label='患者姓名' name='name' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='就诊卡号' name='Medicalcard' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='证件号' name='Idcard' rules={[{required:true}]} className={style.itemstyle}>
                        <Input placeholder='请输入'  style={{width:241,height:32,borderRadius:0}}></Input>
                    </Form.Item>
                    <Form.Item label='备注' name='note' className={style.itemstyle}>
                        <Input.TextArea placeholder='请输入备注' style={{ height: 80, borderRadius: 0, resize: 'none', margin: 'auto' }} rows={4} />
                    </Form.Item>
                </Form>
            </Modal>
            {/* 移除黑名单 */}
            <Modal
                onOk={removeOk}
                onCancel={removeCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u268.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>确认移除黑名单</span>
                    </div>
                }
                open={isDeleteModalVisible}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={removeCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={removeloading} onClick={removeOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
                width={375}
            >
                <p style={{paddingLeft:30 ,color:'#7f7f7f'}}>是否继续操作移除黑名单操作？</p>
            </Modal>
            {/* 详情对话框 */}
            <Modal
                title={<p className={style.detailstitle}>爽约详情</p>}
                open={isdetails}
                footer={false}
                width={725}
                onCancel={detailsClose}
            >
                <Table className={style.detailstable} dataSource={appointmentData} pagination={false} columns={columnstwo} />
            </Modal>
            {/* 搜索盒子 */}
            <div className={style.searchboxs}>
                <Form
                    form={form}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        flexWrap: 'wrap'
                    }}
                    initialValues={{ status: '全部状态' }}
                >
                    <Form.Item label='就诊卡号' rules={[{
                        required:true
                    }]} name='Medicalcard' className={style.inputbox} colon={false}>
                        <Input style={{
                            width: 200,
                            height: 32
                        }} placeholder='请输入'></Input>
                    </Form.Item>
                    <Form.Item label='证件号' rules={[{
                        required:true
                    }]} name='IDcard' className={style.inputbox} colon={false}>
                        <Input style={{
                            width: 200,
                            height: 32
                        }} placeholder='请输入'></Input>
                    </Form.Item>
                    <Form.Item label='患者姓名' rules={[{
                        required:true
                    }]} name='name' className={style.inputbox} colon={false}>
                        <Input style={{
                            width: 200,
                            height: 32
                        }} placeholder='请输入'></Input>
                    </Form.Item>
                    <Flex style={{ width: '100%' }} justify='space-between'>
                        <Form.Item label='状态' name='status' colon={false} className={style.inputbox}>
                            <Select
                                allowClear
                                placeholder='请选择'
                                style={{ width: 200, height: 32 }}
                                options={[
                                    { value: '全部状态', label: '全部状态' },
                                    { value: '未限制', label: '未限制' },
                                    { value: '已限制', label: '已限制' }
                                ]}
                            />
                        </Form.Item>
                        <div className={style.buttonbox}>
                            <Button style={{
                                width: 61,
                                height: 32,
                                marginRight: 10
                            }} onClick={() => reset()}>重置</Button>
                            <Button style={{
                                width: 75,
                                height: 32
                            }} type="primary" onClick={() => search()} icon={<SearchOutlined />}>
                                搜索
                            </Button>
                        </div>
                    </Flex>
                </Form>
            </div>
            {/* 数据列表 */}
            <div className={style.datalists}>
                <Flex style={{ width: '100%' }} justify='space-between'>
                    <div>
                        <Button style={{
                            color: '#0460ff',
                            borderColor: '#0460ff',
                            width: 115,
                            height: 32,
                            marginRight: 10
                        }} icon={<MinusCircleOutlined />} onClick={() => removebatch()}>移出黑名单</Button>
                        <Button style={{
                            color: '#0460ff',
                            borderColor: '#0460ff',
                            width: 75,
                            height: 32
                        }} icon={<UploadOutlined />} onClick={() => exports()}>导出</Button>
                    </div>
                    <Button style={{
                        width: 116,
                        height: 32,
                        borderRadius: 0
                    }} type="primary" onClick={() => insert()} icon={<PlusOutlined />}>
                        新增黑名单
                    </Button>
                </Flex>
                <div ref={tableRef}>
                    <Table<DataType>
                        rowSelection={{ type: 'checkbox', ...rowSelection }}
                        columns={columns}
                        rowKey='blacklist_id'
                        dataSource={data}
                        pagination={false}
                        className={style.tabledata}
                    />
                </div>
                {/* 分页器 */}
                <Padination total={mockData.length} showsize={getshowsize}></Padination>
            </div>
        </>
    );
}

export default Blacklistmanagement;